from api.position import update_symbol_info
from api.market import fetch_binance_ticker_data,load_market
from utils.commons import robust
import math
import ccxt
from config import *
from api.trade import place_order

def clear_pos(exchange):
    """
    一键清仓脚本
    :param exchange:
    :return:
    """
    exchange_info = robust(exchange.fapiPublic_get_exchangeinfo,func_name='fapiPublic_get_exchangeinfo')  # 获取合约信息
    _symbol_list = [x['symbol'] for x in exchange_info['symbols']]
    _symbol_list = [symbol for symbol in _symbol_list if symbol.endswith('USDT')]  # 过滤usdt合约
    # ===从exchange_info中获取每个币种最小交易量
    min_qty = {x['symbol']: int(math.log(float(x['filters'][1]['minQty']), 0.1)) for x in exchange_info['symbols']}
    # 案例：{'BTCUSDT': 3, 'ETHUSDT': 3, 'BCHUSDT': 3, 'XRPUSDT': 1, 'EOSUSDT': 1, 'LTCUSDT': 3, 'TRXUSDT': 0}

    # ===从exchange_info中获取每个币种下单精度
    price_precision = {x['symbol']: int(math.log(float(x['filters'][0]['tickSize']), 0.1)) for x in
                       exchange_info['symbols']}
    # 案例：{'BTCUSDT': 2, 'ETHUSDT': 2, 'BCHUSDT': 2, 'XRPUSDT': 4, 'EOSUSDT': 3, 'LTCUSDT': 2, 'TRXUSDT': 5, 'ETCUSDT': 3}

    symbol_info = update_symbol_info(exchange, _symbol_list)
    symbol_info['目标下单份数'] = 0
    symbol_info['目标下单量'] = 0
    symbol_info['当前持仓量'] = symbol_info['当前持仓量'].astype(float)
    symbol_info = symbol_info[symbol_info['当前持仓量'] != 0.00]

    # =====计算实际下单量
    symbol_info['实际下单量'] = - symbol_info['当前持仓量']
    # =====获取币种的最新价格
    symbol_last_price = fetch_binance_ticker_data(exchange)
    for k in symbol_last_price.keys():
        symbol_last_price[k]=float(symbol_last_price[k])

    # =====逐个下单
    min_notional = load_market(exchange, [])
    place_order(exchange, symbol_info, symbol_last_price, min_qty, price_precision,min_notional)


if __name__=='__main__':
    exchange = ccxt.binance(BINANCE_CONFIG)
    exchange.proxies = proxy
    clear_pos(exchange)